<!--
  @Description:商品权限配置编辑
  @Author:zqy
  @Date:2022-12-16 14:44:32
  @Last Modified by:zqy
  @Last Modified time:2022-12-16 14:44:32
-->
<template>
  <el-dialog
    ref="formDlg"
    :title="`${!!(detail && detail.id)?'编辑':'新增'}权限配置`"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="500px"
    @close="closeDialog"
  >
    <div style="padding-right:30px">
      <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="100px">
        <el-form-item label="商品特殊标识:" prop="goodsAttrSpecialIdentification">
          <qup-search-select-picker
            :url="specialLabelApi"
            placeholder="请选择"
            lable-name="description"
            value-name="id"
            method="get"
            :params="{query:{},type:0}"
            :value.sync="formData.goodsAttrSpecialIdentification"
            :lable.sync="formData.speLabelName"
            @change="handleSpeLabelChange"
          />
        </el-form-item>
        <el-form-item label="角色权限:" prop="roleNames">
          <el-input v-model="formData.roleNames" placeholder="请选择" @focus="handleOpenRole">
            <div slot="suffix">
              <i
                v-if="!!(formData.roleNames)"
                class="el-input__icon el-icon-circle-close"
                @click.self="hanldeClearRole"
              />
              <i class="el-input__icon el-icon-search" @click.self="handleOpenRole" />
            </div>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button v-loading="submiting" size="mini" type="primary" @click="submitForm">保存</el-button>
    </div>
    <RoleDlg
      v-if="showRoleDlg"
      multiple
      :visible.sync="showRoleDlg"
      @change="handleRoleChange"
    />
  </el-dialog>
</template>

<script>
import RoleDlg from '@/components/RoleDlg/index'
import { saveRoleRelation } from '@/api/productAuthConfig'
export default {
  name: 'ProductAuthConfigEdit',
  components: { RoleDlg },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      specialLabelApi: `${process.env.VUE_APP_BASE_API}/api/v1/productSearchRoleRelation/querySpecialLabelItems`,
      formData: {
        id: null,
        roleIds: '',
        roleNames: '',
        speLabelName: '',
        goodsAttrSpecialIdentification: ''
      },
      formRules: {
        goodsAttrSpecialIdentification: [
          { required: true, message: '请选择商品特殊标识', trigger: 'change' }
        ],
        roleNames: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      permissionRoles: [], // 当前所选角色
      submiting: false,
      showSpecailLabel: false,
      showRoleDlg: false
    }
  },

  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    if (this.detail && this.detail.id) {
      const data = this.detail
      const speLabelName = ''
      this.formData = {
        id: data.id,
        roleNames: data.roleNames,
        roleIds: data.roleIds || '',
        speLabelName,
        goodsAttrSpecialIdentification: data.goodsAttrSpecialIdentification
      }
      if (![undefined, null, ''].includes(data.roleIds)) {
        const rolesIds = data.roleIds.split(',')
        this.permissionRoles = rolesIds.map(id => {
          return {
            roleId: id
          }
        })
      }
    }
  },

  methods: {
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    clearForm(done) {
      this.formData = {
        id: null,
        roleNames: '',
        roleIds: '',
        goodsAttrSpecialIdentification: '',
        speLabelName: ''
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    submitForm(type) {
      if (this.submiting) return
      this.$refs['refForm'].validate(async(valid) => {
        if (valid) {
          const formData = Object.assign(this.formData)
          delete formData.speLabelName
          this.submiting = true
          await saveRoleRelation(formData).then(res => {
            this.submiting = false
            if (res.success === 1) {
              this.$message({
                message: `${formData.id ? '编辑' : '新增'}保存成功`,
                type: 'success'
              })
              this.$emit('success', !formData.id)
              this.closeDialog()
            }
          }).catch(() => {
            this.submiting = false
          })
        }
      })
    },
    // 商品标识变更
    handleSpeLabelChange(data) {
      // console.log('商品标识变更', data)
    },
    // 清空角色
    hanldeClearRole() {
      this.permissionRoles = []
      this.$set(this.formData, 'roleNames', '')
      this.$set(this.formData, 'roleIds', '')
    },
    // 打开角色选择
    handleOpenRole() {
      this.showRoleDlg = true
    },
    handleRoleChange(data) {
      const list = data || []
      const ids = []
      const names = list.map(v => {
        ids.push(v.roleId)
        return v.roleName
      })
      this.$set(this.formData, 'roleNames', names.join(','))
      this.$set(this.formData, 'roleIds', ids.join(','))
      this.permissionRoles = list
    }
  }
}
</script>
<style lang='scss' scoped>

</style>
